import ReactDOM from 'react-dom/client';

import { App as AntdApp, ConfigProvider } from 'antd';
import zh_CN from 'antd/locale/zh_CN';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import relativeTime from 'dayjs/plugin/relativeTime';
import { configure } from 'mobx';

import { StyleProvider, legacyLogicalPropertiesTransformer } from '@ant-design/cssinjs';
import { addCollection } from '@iconify/react';

import { App } from './app';
import { store } from './store';
import './store/layout';
import './styles/index.scss';
import { request } from './utils/api';

dayjs.locale('zh-cn');
dayjs.extend(relativeTime);

configure({ enforceActions: 'never' });

// 加载图标
fetch('./icons/ri-raw.json')
  .then((r) => r.json())
  .then((data) => {
    store.icon[data.prefix] = data.categories;
    // console.log(data.categories)
    addCollection(data);
  })
  .catch(() => {});

const compareVersion = async () => {
  const local_version = VERSION;

  try {
    const res = await fetch(`./version.json?t=${Date.now()}`).then((r) => r.json());

    if (res.version && local_version !== res.version) {
      window.location.reload();
    }
  } catch (error) {
    console.log('compareVersion', error);
  }
};

(async () => {
  if (import.meta.env.MODE === 'production') {
    // 版本比较间隔
    const interval = 30 * 1000; // 30秒

    while (true) {
      await compareVersion();

      await new Promise((r) => {
        setTimeout(r, interval);
      });
    }
  }
})();
(async () => {
  const token = localStorage.getItem('token');

  if (token) {
    const user = await store.getUserInfoByToken(token);

    if (user) {
      // 设置token, 可能在retryCondition已经设置了新的token, 这里需要判断一下
      request.defaults.headers.token = request.defaults.headers.token || token;
    }
  }

  ReactDOM.createRoot(document.getElementById('root')!).render(
    <>
      <ConfigProvider
        locale={zh_CN}
        wave={{ disabled: true }}
        theme={{
          cssVar: true,
          inherit: true,
          hashed: false,
          // algorithm: [theme.compactAlgorithm],
          token: {
            // motion: false,
            colorPrimary: '#af831e',
            colorLink: '#af831e',
            borderRadius: 4
          },
          components: {
            Menu: {
              collapsedWidth: 48
            }
          }
        }}
      >
        <StyleProvider hashPriority="high" transformers={[legacyLogicalPropertiesTransformer]}>
          <AntdApp>
            <>
              <App />
            </>
          </AntdApp>
        </StyleProvider>
      </ConfigProvider>
    </>
  );
})();
